﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using BLL;
using DevExpress.Web;
using Entity;
using Platform.Menu;
using Web.Class;
using MenuItem = Platform.Menu.MenuItem;
using System.Data;

namespace Web.AuthorizationSystem
{
    public partial class UserPermission : Page
    {
        private List<MenuItem> menuItems;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadDepartment();
                menuItems = LoadMenu();
                BindMenu();
            }
        }

        protected void btnSearch_OnClick(object sender, EventArgs e)
        {
            var name = txtUserName.Text;
            var department = -1;
            if (comboDepartment.SelectedItem != null)
                department = Convert.ToInt32(comboDepartment.SelectedItem.Value);
            List<XTUSER> list = new DALXTUSER().Get(name, department, 1);
            gridUser.DataSource = list;
            gridUser.DataBind();
        }

        private void LoadDepartment()
        {
            var list = new DALCommon().GetDDLItemList("YS_JX_BUMENXX", "S_MINGCHENG", "S_BIANHAO", "", "I_JLZT=0", "S_BIANHAO ASC");
            foreach (var item in list)
            {
                comboDepartment.Items.Add(new ListEditItem(item.Text, item.Value));
            }
        }

        private List<MenuItem> LoadMenu()
        {
            var helper = new SqlHelper();
            var code = Request.Cookies["code"].Value;
            var dt = helper.GetMenuByCode(code).Tables[0];
            var list = CreateMenuList(dt);
            return list;
        }

        private List<MenuItem> CreateMenuList(DataTable dt)
        {
            var list = new List<MenuItem>();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                var menuItem = new MenuItem
                {
                    BelongID = dt.Rows[i]["BELONGID"] == null ? 0 : Convert.ToInt32(dt.Rows[i]["BELONGID"]),
                    DisplayIndex = dt.Rows[i]["DISPLAYINDEX"] == null ? 0 : Convert.ToInt32(dt.Rows[i]["DISPLAYINDEX"]),
                    Event = Convert.ToString(dt.Rows[i]["EVENT"]),
                    ImageLink = Convert.ToString(dt.Rows[i]["IMAGELINK"]),
                    MdiChildForm = dt.Rows[i]["MDICHILDFORM"] == null ? 0 : Convert.ToInt32(dt.Rows[i]["MDICHILDFORM"]),
                    MenuHeight = dt.Rows[i]["MENUHEIGHT"] == DBNull.Value
                        ? 0
                        : Convert.ToInt32(dt.Rows[i]["MENUHEIGHT"]),
                    MenuID = dt.Rows[i]["MENUID"] == null ? 0 : Convert.ToInt32(dt.Rows[i]["MENUID"]),
                    MenuName = Convert.ToString(dt.Rows[i]["MENUNAME"]),
                    MenuWidth = dt.Rows[i]["MENUWIDTH"] == DBNull.Value ? 0 : Convert.ToInt32(dt.Rows[i]["MENUWIDTH"]),
                    PermissionID = Convert.ToString(dt.Rows[i]["PERMISSIONID"])
                };
                var picmode = dt.Rows[i]["PICMODE"] == DBNull.Value ? 0 : Convert.ToInt32(dt.Rows[i]["PICMODE"]);
                switch (picmode)
                {
                    case 0:
                        menuItem.PicMode = MenuItemPicMode.None;
                        break;
                    case 1:
                        menuItem.PicMode = MenuItemPicMode.Small;
                        break;
                    case 2:
                        menuItem.PicMode = MenuItemPicMode.Large;
                        break;
                }
                menuItem.Remark = Convert.ToString(dt.Rows[i]["REMARK"]);
                menuItem.Status = dt.Rows[i]["STATUS"] == null ? 0 : Convert.ToInt32(dt.Rows[i]["STATUS"]);
                menuItem.WindowMode = dt.Rows[i]["WINDOWSTATE"] == null ? 0 : Convert.ToInt32(dt.Rows[i]["WINDOWSTATE"]);
                menuItem.WindowState = dt.Rows[i]["WINDOWMODE"] == null ? 0 : Convert.ToInt32(dt.Rows[i]["WINDOWMODE"]);
                list.Add(menuItem);
            }
            return list;
        }

        private void BindMenu()
        {
            var rootMenus = menuItems.Where(m => m.BelongID == 0).OrderBy(m => m.DisplayIndex).ToList();
            foreach (var rootMenu in rootMenus)
            {
                var node = new TreeNode(text: rootMenu.MenuName, value: rootMenu.MenuID.ToString());
                CreateChildNode(ref node,rootMenu);
                crTreeViewAllPermission.Nodes.Add(node);
            }
        }

        private void CreateChildNode(ref TreeNode node,MenuItem item)
        {
            var childMenus = menuItems.Where(m => m.BelongID == item.MenuID).OrderBy(m => m.DisplayIndex).ToList();
            if (childMenus.Count > 0)
            {
                foreach (var childMenu in childMenus)
                {
                    var childNode = new TreeNode(childMenu.MenuName, childMenu.MenuID.ToString());
                    CreateChildNode(ref childNode,childMenu);
                    node.ChildNodes.Add(childNode);
                }
            }
        }

        protected void lnbModify_OnCommand(object sender, CommandEventArgs e)
        {
            crTreeViewAllPermission.Enabled = true;
            btnSave.Enabled = true;
            btnCancel.Enabled = true;
            crTreeViewAllPermission.Nodes.Clear();
            menuItems = LoadMenu();
            BindMenu();
            var userId = Convert.ToInt32(e.CommandArgument);
            var code = Request.Cookies["code"].Value;
            var permissions = new SqlHelper().GetUserPermission(code, userId).Tables[0];
            for (int i = 0; i < permissions.Rows.Count; i++)
            {
                int menuId = Convert.ToInt32(permissions.Rows[i]["MENU_ID"]);
                foreach (var node in crTreeViewAllPermission.Nodes)
                {
                    var rootNode = node as TreeNode;
                    CheckNode(menuId,ref rootNode);
                }
            }
            var rolePermissons = new SqlHelper().GetUserRolePermisson(userId, code).Tables[0];
            for (int i = 0; i < rolePermissons.Rows.Count; i++)
            {
                int menuId = Convert.ToInt32(rolePermissons.Rows[i]["MENUID"]);
                foreach (var node in crTreeViewAllPermission.Nodes)
                {
                    var rootNode = node as TreeNode;
                    CheckNode(menuId, ref rootNode);
                }
            }
            ViewState["CurrentUser"] = userId;
        }

        private void CheckNode(int menuId,ref TreeNode parentNode)
        {
            if (parentNode.Value == menuId.ToString())
            {
                parentNode.Checked = true;
            }
            else
            {
                foreach (var node in parentNode.ChildNodes)
                {
                    var childNode = node as TreeNode;
                    CheckNode(menuId,ref childNode);
                }
            }
        }


        protected void btnSave_OnClick(object sender, EventArgs e)
        {
            var userId = Convert.ToInt32(ViewState["CurrentUser"]);
            var code = Request.Cookies["code"].Value;
            var removeResult = new SqlHelper().RemoveUserPermission(code, userId);
            if (removeResult)
            {
                foreach (var node in crTreeViewAllPermission.Nodes)
                {
                    var rootNode = node as TreeNode;
                    SaveNode(ref rootNode);
                }
                crTreeViewAllPermission.Enabled = false;
                btnSave.Enabled = false;
                btnCancel.Enabled = false;
                menuItems = LoadMenu();
                BindMenu();
                PageTools.AlertMsg(this,"保存成功,若节点权限是角色权限分配的则修改不生效。");
            }
            else
            {
                PageTools.AlertMsg(this,"保存失败");
            }
        }

        private void SaveNode(ref TreeNode parentNode)
        {
            var userId = Convert.ToInt32(ViewState["CurrentUser"]);
            var code = Request.Cookies["code"].Value;
            if (parentNode.Checked)
            {
                new SqlHelper().AddUserPermission(code, userId, Convert.ToInt32(parentNode.Value));
            }
            foreach (var node in parentNode.ChildNodes)
            {
                var childNode = node as TreeNode;
                SaveNode(ref childNode);
            }
        }

        protected void btnCancel_OnClick(object sender, EventArgs e)
        {
            crTreeViewAllPermission.Nodes.Clear();
            menuItems = LoadMenu();
            BindMenu();
            crTreeViewAllPermission.Enabled = false;
            btnSave.Enabled = false;
            btnCancel.Enabled = false;
        }
    }
}